<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { Delete, Check, Refresh } from '@element-plus/icons-vue';
import api from '@/api';

const mode = ref('inbound');
const form = ref({
  transactionCode: '',
  source: '',
  time: '',
  remark: ''
});

const skuCode = ref('');
const items = ref([]);
const skuCodeInput = ref(null);
const dialogVisible = ref(false);

const dialogForm = ref({
  skuCode: '',
  productCode: '',
  brand: '',
  color: '',
  sizeType: '',
  retailPrice: null
});

const sizeMap = {
  '0': 'F', '1': 'XS', '2': 'S', '3': 'M', '4': 'L', '5': 'XL', '6': '2XL', '7': '3XL'
};

const brandItems = ref([
  { value: '路易丝', label: '路易丝' }
]);
const colorItems = ref([
  { value: '黑', label: '黑' },
  { value: '白', label: '白' },
  { value: '红', label: '红' },
  { value: '蓝', label: '蓝' },
  { value: '黄', label: '黄' },
  { value: '绿', label: '绿' }
]);

const isAddingBrand = ref(false);
const isAddingColor = ref(false);
const optionNameBrand = ref('');
const optionNameColor = ref('');

const addOption = (collection, optionInput, isAddingRef) => {
  if (!optionInput.value.trim()) {
    ElMessage.warning(`请输入${collection === brandItems ? '品牌' : '颜色'}名称`);
    return;
  }
  if (collection.value.some(item => item.value === optionInput.value)) {
    ElMessage.warning(`该${collection === brandItems ? '品牌' : '颜色'}已存在`);
    return;
  }
  collection.value.push({
    label: optionInput.value,
    value: optionInput.value
  });
  ElMessage.success(`添加${collection === brandItems ? '品牌' : '颜色'}成功`);
  clearOption(optionInput, isAddingRef);
};

const clearOption = (optionInput, isAddingRef) => {
  optionInput.value = '';
  isAddingRef.value = false;
};

const onAddBrandOption = () => {
  isAddingBrand.value = true;
};

const onConfirmBrand = () => {
  addOption(brandItems, optionNameBrand, isAddingBrand);
};

const clearBrand = () => {
  clearOption(optionNameBrand, isAddingBrand);
};

const onAddColorOption = () => {
  isAddingColor.value = true;
};

const onConfirmColor = () => {
  addOption(colorItems, optionNameColor, isAddingColor);
};

const clearColor = () => {
  clearOption(optionNameColor, isAddingColor);
};

const generateTransactionCode = () => {
  const date = new Date().toISOString().slice(0, 10).replace(/-/g, '');
  const prefix = mode.value === 'inbound' ? 'IN' : 'OUT';
  return `${prefix}${date}${Math.floor(Math.random() * 1000).toString().padStart(3, '0')}`;
};

const handleModeChange = () => reset();

const handleScan = async () => {
  if (!skuCode.value.trim()) return;

  // 检查前端已录入商品列表中是否已存在该SKU码
  const existingItem = items.value.find(item => item.skuCode === skuCode.value);
  if (existingItem) {
    ElMessage.warning(`该商品（SKU: ${skuCode.value}）已在本单中录入，请勿重复添加！`);
    skuCode.value = '';
    return;
  }

  try {
    const response = await api.inventoryTransaction.checkSku({ skuCode: skuCode.value });
    
    // 入库模式：如果商品已存在(code=1)，则不应该入库
    if (mode.value === 'inbound' && response.code === 1) {
      ElMessage.error(`该商品已存在于库存中（SKU: ${skuCode.value}），不能重复入库！`);
      skuCode.value = '';
      return;
    }
    
    // 出库模式：如果商品不存在(code=0)，则不应该出库
    if (mode.value === 'outbound' && response.code === 0) {
      ElMessage.error(`库存中无该商品（SKU: ${skuCode.value}），出库失败！`);
      skuCode.value = '';
      return;
    }

    // 出库模式：商品存在，可以出库
    if (mode.value === 'outbound' && response.code === 1) {
      try {
        // 获取商品详情
        const detailResponse = await api.inventoryTransaction.getSkuDetail({ skuCode: skuCode.value });
        if (detailResponse.code === 1 && detailResponse.data) {
          // 使用后端返回的数据填充列表
          items.value.push({
            skuCode: skuCode.value,
            brand: detailResponse.data.brand || '',
            productCode: detailResponse.data.productCode || '',
            color: detailResponse.data.color || '',
            sizeType: detailResponse.data.sizeType || '',
            retailPrice: detailResponse.data.retailPrice || null
          });
          ElMessage.success(`SKU编码 ${skuCode.value} 已添加`);
        } else {
          // 如果获取详情失败，仍然添加SKU，但其他字段为空
          items.value.push({
            skuCode: skuCode.value,
            brand: '',
            productCode: '',
            color: '',
            sizeType: '',
            retailPrice: null
          });
          ElMessage.warning(`SKU编码 ${skuCode.value} 已添加，但获取商品详情失败`);
        }
      } catch (error) {
        // 如果获取详情出错，仍然添加SKU，但其他字段为空
        items.value.push({
          skuCode: skuCode.value,
          brand: '',
          productCode: '',
          color: '',
          sizeType: '',
          retailPrice: null
        });
        ElMessage.warning(`SKU编码 ${skuCode.value} 已添加，但获取商品详情失败: ${error.msg || error.message || '未知错误'}`);
      }
      skuCode.value = '';
      skuCodeInput.value?.focus();
      return;
    }

    // 入库模式：商品不存在，可以入库，弹出 dialog 输入详细信息
    if (mode.value === 'inbound' && response.code === 0) {
      dialogForm.value = {
        skuCode: skuCode.value,
        productCode: '',
        brand: '',
        color: '',
        sizeType: '',
        retailPrice: null
      };
      dialogVisible.value = true;
      skuCode.value = '';
      skuCodeInput.value?.focus();
    }
  } catch (error) {
    ElMessage.error(`扫码失败: ${error.msg || error.message || '未知错误'}`);
    skuCode.value = '';
    skuCodeInput.value?.focus();
  }
};

const saveItem = () => {
  const { skuCode, productCode, brand, color, sizeType, retailPrice } = dialogForm.value;
  if (!skuCode || !productCode || !brand || !color || sizeType === '' || retailPrice === null || retailPrice === '') {
    return ElMessage.warning('请完整填写商品信息');
  }
  if (isNaN(retailPrice) || retailPrice < 0) {
    return ElMessage.warning('零售价必须是有效的非负数字');
  }
  
  // 检查前端已录入商品列表中是否已存在该SKU码
  const existingItem = items.value.find(item => item.skuCode === skuCode);
  if (existingItem) {
    return ElMessage.warning(`该商品（SKU: ${skuCode}）已在本单中录入，请勿重复添加！`);
  }
  
  items.value.push({ ...dialogForm.value });
  dialogVisible.value = false;
  ElMessage.success(`SKU编码 ${skuCode} 已绑定`);
  skuCodeInput.value?.focus();
};

const removeItem = (index) => items.value.splice(index, 1);

const submit = async () => {
  if (!form.value.transactionCode || !form.value.source || !form.value.time) {
    return ElMessage.warning('请填写完整的出入库信息');
  }
  if (!items.value.length) return ElMessage.warning('请至少录入一件商品');

  const invalidItem = items.value.find(item =>
    !item.skuCode || !item.brand || !item.productCode || !item.color ||
    item.sizeType === '' || item.retailPrice === null || item.retailPrice === ''
  );
  if (invalidItem) return ElMessage.warning('请完整填写每件商品信息');

  const payload = {
    transactionCode: form.value.transactionCode,
    source: form.value.source,
    time: form.value.time,
    remark: form.value.remark,
    details: items.value.map(item => ({
      skuCode: item.skuCode,
      brand: item.brand,
      productCode: item.productCode,
      color: item.color,
      sizeType: parseInt(item.sizeType),
      retailPrice: item.retailPrice
    }))
  };

  try {
    const response = await api.inventoryTransaction.submitTransaction(mode.value, payload);
    if (response.code === 1) {
      ElMessage.success(mode.value === 'inbound' ? '入库成功' : '出库成功');
      reset();
    } else {
      ElMessage.error(response.msg || (mode.value === 'inbound' ? '入库失败' : '出库失败'));
    }
  } catch (error) {
    ElMessage.error(`操作失败: ${error.msg || error.message || '未知错误'}`);
  }
};

const reset = () => {
  // 重置单据信息
  form.value = {
    transactionCode: generateTransactionCode(),
    source: '',
    time: '',
    remark: ''
  };
  // 清空商品列表
  items.value = [];
  // 清空 SKU 输入框
  skuCode.value = '';
  // 重置对话框表单
  dialogForm.value = {
    skuCode: '',
    productCode: '',
    brand: '',
    color: '',
    sizeType: '',
    retailPrice: null
  };
  // 关闭对话框
  dialogVisible.value = false;
  // 重置品牌和颜色输入状态
  isAddingBrand.value = false;
  isAddingColor.value = false;
  optionNameBrand.value = '';
  optionNameColor.value = '';
  // 确保 UI 刷新后聚焦到输入框
  nextTick(() => {
    skuCodeInput.value?.focus();
  });
};

onMounted(() => reset());
</script>
<template>
  <div class="inventory-container">
    <el-tabs v-model="mode" @tab-click="handleModeChange">
      <el-tab-pane label="商品入库" name="inbound" />
      <el-tab-pane label="商品出库" name="outbound" />
    </el-tabs>

    <el-card shadow="hover" style="margin-bottom: 20px">
      <template #header>
        <span>出入库单信息</span>
      </template>
      <el-form :model="form" label-width="100px">
        <el-form-item label="单号">
          <el-input v-model="form.transactionCode" disabled />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="来源/目的地">
              <el-input v-model="form.source" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="出入库时间">
          <el-date-picker v-model="form.time" type="datetime" placeholder="选择时间" value-format="YYYY-MM-DD HH:mm" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="hover">
      <template #header>
        <span>商品录入</span>
      </template>
      <el-input
        v-model="skuCode"
        placeholder="扫码器扫码SKU编码或手动输入"
        @keyup.enter="handleScan"
        ref="skuCodeInput"
      />
      <el-table :data="items" border stripe style="margin-top: 10px">
        <el-table-column prop="skuCode" label="SKU编码" />
        <el-table-column prop="brand" label="品牌" />
        <el-table-column prop="productCode" label="款号" />
        <el-table-column prop="color" label="颜色" />
        <el-table-column prop="retailPrice" label="零售价" />
        <el-table-column label="尺码">
          <template #default="scope">
            {{ sizeMap[scope.row.sizeType] }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="danger" size="small" @click="removeItem(scope.$index)" circle>
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div style="margin-top: 20px; text-align: right">
      <el-button type="success" size="large" @click="submit">
        <el-icon><Check /></el-icon> 提交
      </el-button>
      <el-button size="large" @click="reset">
        <el-icon><Refresh /></el-icon> 重置
      </el-button>
    </div>

    <el-dialog v-model="dialogVisible" title="商品信息" width="500px">
      <el-form :model="dialogForm" label-width="80px">
        <el-form-item label="SKU编码">
          <el-input v-model="dialogForm.skuCode" disabled />
        </el-form-item>
        <el-form-item label="品牌">
          <el-select v-model="dialogForm.brand" filterable placeholder="请选择品牌">
            <el-option
              v-for="item in brandItems"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
            <template #footer>
              <el-button v-if="!isAddingBrand" text bg size="small" @click="onAddBrandOption">+</el-button>
              <template v-else>
                <el-input
                  v-model="optionNameBrand"
                  class="option-input"
                  placeholder="创建新的品牌"
                  size="small"
                />
                <el-button type="primary" size="small" @click="onConfirmBrand">添加</el-button>
                <el-button size="small" @click="clearBrand">取消</el-button>
              </template>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="款号">
          <el-input v-model="dialogForm.productCode" placeholder="请输入款号" />
        </el-form-item>
        <el-form-item label="颜色">
          <el-select v-model="dialogForm.color" filterable placeholder="请选择颜色">
            <el-option
              v-for="item in colorItems"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
            <template #footer>
              <el-button v-if="!isAddingColor" text bg size="small" @click="onAddColorOption">+</el-button>
              <template v-else>
                <el-input
                  v-model="optionNameColor"
                  class="option-input"
                  placeholder="创建新的颜色"
                  size="small"
                />
                <el-button type="primary" size="small" @click="onConfirmColor">添加</el-button>
                <el-button size="small" @click="clearColor">取消</el-button>
              </template>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="零售价">
          <el-input v-model.number="dialogForm.retailPrice" placeholder="请输入零售价" type="number" />
        </el-form-item>
        <el-form-item label="尺码">
          <el-select v-model="dialogForm.sizeType" placeholder="请选择">
            <el-option v-for="(label, key) in sizeMap" :key="key" :label="label" :value="key" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveItem">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.inventory-container {
  padding: 20px;
}
.option-input {
  width: 200px;
  margin-right: 10px;
}
</style>